package com.ruoyi.feike.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.feike.controller.PdfController;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.BasicInformationVO;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * feikeService业务层处理
 *
 * @author zmh
 * @date 2022-07-05
 */
@Service
public class BasicInformationServiceImpl implements IBasicInformationService {
    @Autowired
    private BasicInformationMapper basicInformationMapper;
    @Autowired
    private ApprovedLimitAndConditionMapper approvedLimitAndConditionMapper;
    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;
    @Autowired
    private IBasicContractService basicContractService;
    @Autowired
    private IDealerSectorLimitflagService dealerSectorLimitflagService;
    @Autowired
    private IDealerSectorContractgroupService dealerSectorContractgroupService;
    @Autowired
    private IGuaranteeInformationService guaranteeInformationService;
    @Autowired
    private ICreditConditionService creditConditionService;
    @Autowired
    private IWholesalePerformanceCurrentlyService wholesalePerformanceCurrentlyService;
    @Autowired
    private IDealercodeContractService dealercodeContractService;
    @Autowired
    private PdfController pdfController;
    @Autowired
    private IDealercodeCountService dealercodeCountService;
    @Autowired
    private IBasicInformationService basicInformationService;
    @Autowired
    private DealercodeContractMapper dealercodeContractMapper;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public BasicInformation selectBasicInformationById(String id) {
        return basicInformationMapper.selectBasicInformationById(id);
    }

    /**
     * 查询feike列表
     *
     * @param basicInformation feike
     * @return feike
     */
    @Override
    public List<BasicInformation> selectBasicInformationList(BasicInformation basicInformation) {
        return basicInformationMapper.selectBasicInformationList(basicInformation);
    }

    /**
     * 新增feike
     *
     * @param basicInformation feike
     * @return 结果
     */
    @Override
    public int insertBasicInformation(BasicInformation basicInformation) {
        return basicInformationMapper.insertBasicInformation(basicInformation);
    }

    @Override
    public int insertBasicInformationByDto(BasicInformationDTO basicInformation) {
        return basicInformationMapper.insertBasicInformationByDto(basicInformation);
    }


    /**
     * 修改feike
     *
     * @param basicInformation feike
     * @return 结果
     */
    @Override
    public int updateBasicInformation(BasicInformation basicInformation) {
        return basicInformationMapper.updateBasicInformation(basicInformation);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteBasicInformationByIds(String[] ids) {
        return basicInformationMapper.deleteBasicInformationByIds(ids);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteBasicInformationById(String id) {
        return basicInformationMapper.deleteBasicInformationById(id);
    }

    /**
     * 根据合同规则修改相应的PriorityID字段
     *
     * @param resultMap
     * @return 结果
     */
    @Override
    public int updateBasicInformationRules(Map<String, Object> resultMap) {
        List<BasicInformationVO> basicInformations = JSONObject.parseArray(JSON.toJSONString(resultMap.get("priority")), BasicInformationVO.class);
        for (BasicInformationVO basicInformationVO : basicInformations) {
            BasicInformation basicInformation = selectBasicInformationById(basicInformationVO.getDealerId());
            basicInformation.setPriorityId(basicInformation.getId());
            basicInformation.setPriority(basicInformationVO.getPriority());
            updateBasicInformation(basicInformation);
        }

        //根据优先级，主机厂，授信类型查合同表里对应得合同，返回他的合同名称和合同地址

//        BasicInformation basicInformation = new BasicInformation();
//        basicInformation.setId(dealerid);
//        List<BasicInformation> dealerInformations = basicInformationMapper.selectDealerInformationList(dealerInformation);
//        BasicInformation basicInformation = selectBasicInformationById(basicInformations);
//        BasicInformation dealerInformation1 = dealerInformations.get(0);
//        basicInformation.setPriorityId(basicInformation.getId());
//        basicInformation.setPriority(priority);

        return 1;
    }

    //根据合同规则判断属于什么优先级然后再根据单条信息字段查匹配的合同
    @Override
    public Map<String, Object> matchTheContract(Map<String, Object> resultMap) {
        String dealerId = (String) resultMap.get("dealerId");
        String instanceId = (String) resultMap.get("instanceId");
        ApprovedLimitAndCondition approvedLimitAndCondition = new ApprovedLimitAndCondition();
        approvedLimitAndCondition.setDealerid(dealerId);
        approvedLimitAndCondition.setInstanceid(instanceId);
        List<ApprovedLimitAndCondition> approvedLimitAndConditions = approvedLimitAndConditionMapper.selectApprovedLimitAndConditionList(approvedLimitAndCondition);
        Map<String, Object> mapmtc = new HashMap<>();
        for (ApprovedLimitAndCondition alac : approvedLimitAndConditions) {
            if ((alac.getApprovedlimit() == null && alac.getApprovedcashdeposit() == null) && (alac.getProposallimit() != null && alac.getProposalcashdeposit() != null)) {
                Map<String, Object> map = new HashMap<>();
                map.put("priority", "4");
                map.put("sector", alac.getSector());
                map.put("limitType", alac.getLimittype());
                List<BasicContract> basicContracts = basicContractService.listBasicContract(map);
                mapmtc.put("BasicContract", basicContracts);
            }
        }
        return mapmtc;
    }

    //直接从生成的合同记录表里拿数据并拼接
    @Override
    public List contracts(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        DealercodeContract dealercodeContract = new DealercodeContract();
        dealercodeContract.setInstanceId(instanceId);
        List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.dealercodeContractListgroupby(dealercodeContract);

        for(DealercodeContract applac : dealercodeContracts) {
            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).get("id").equals(applac.getDealerNameCN())){
                    objectObjectHashMap2 = list.get(i);
                }
            }
//            Map<String, Object> map = new HashMap<>();
            ArrayList<Map<String, Object>> list1 = new ArrayList<>();
            Map<String, Object> objectObjectHashMap3 = new HashMap<>();
//            map.put("Dealername", applac.getDealername());
//            map.put("sector", applac.getSector());
//            map.put("instanceId", instanceId);
//            List<BasicContract> basicContracts = this.matchTheContractNew(map);
            DealercodeContract dealercodeContract1 = new DealercodeContract();
            dealercodeContract1.setDealerNameCN(applac.getDealerNameCN());
            dealercodeContract1.setSector(applac.getSector());
            dealercodeContract1.setInstanceId(instanceId);
            List<DealercodeContract> dealercodeContracts1 = dealercodeContractService.selectDealercodeContractList(dealercodeContract1);

            objectObjectHashMap2.put("id", applac.getDealerNameCN());
            objectObjectHashMap2.put("dealername", applac.getDealerNameCN());
            objectObjectHashMap3.put("contractname",applac.getSector());
            objectObjectHashMap3.put("children",dealercodeContracts1);
            list1.add(objectObjectHashMap3);

            if(null!=objectObjectHashMap2.get("children")){
                List<Map<String, Object>> children = (List<Map<String, Object>>) objectObjectHashMap2.get("children");
                children.addAll(list1);
            }else {
                objectObjectHashMap2.put("children", list1);
                list.add(objectObjectHashMap2);

            }
        }
        System.out.println("生成合同中");
        return  list;
    }

    @Override
    public List contract(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        Map<String, Map<String, Object>> objectObjectHashMap = new HashMap<>();

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupby(approvedLimitAndCondition);
//        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTwo = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupbyTwo(approvedLimitAndCondition);
//        ProposalByCommericalAndMarketing proposal = new ProposalByCommericalAndMarketing();
//        List<ProposalByCommericalAndMarketing> proposal1 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposal);
//        for(ProposalByCommericalAndMarketing applacnew : approvedLimitAndConditionsTwo){
//            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
//            objectObjectHashMap2.put("id", applacnew.getDealername());
//            objectObjectHashMap2.put("dealername", applacnew.getDealername());
//            objectObjectHashMap2.put("contractname", applacnew.getSector());
        for(ProposalByCommericalAndMarketing applac : approvedLimitAndConditions) {
            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).get("id").equals(applac.getDealername())){
                    objectObjectHashMap2 = list.get(i);
                }
            }
            Map<String, Object> map = new HashMap<>();
//            Map<String, Object> objectObjectHashMap1 = new HashMap<>();
            ArrayList<Map<String, Object>> list1 = new ArrayList<>();
            Map<String, Object> objectObjectHashMap3 = new HashMap<>();
            map.put("Dealername", applac.getDealername());
            map.put("sector", applac.getSector());
            map.put("instanceId", instanceId);
            List<BasicContract> basicContracts = this.matchTheContractNew(map);

            objectObjectHashMap2.put("id", applac.getDealername());
            objectObjectHashMap2.put("dealername", applac.getDealername());
            objectObjectHashMap3.put("contractname",applac.getSector());
            objectObjectHashMap3.put("children",basicContracts);
            list1.add(objectObjectHashMap3);

            if(null!=objectObjectHashMap2.get("children")){
                List<Map<String, Object>> children = (List<Map<String, Object>>) objectObjectHashMap2.get("children");
                children.addAll(list1);
            }else {
                objectObjectHashMap2.put("children", list1);
                list.add(objectObjectHashMap2);

            }
            //判断是否存在key
//            if (objectObjectHashMap2.containsKey(applac.getDealername())) {
//                //存在就是取当前key的值，再把新值存进去
//                objectObjectHashMap.get(applac.getDealername()).putAll(objectObjectHashMap1);
//
//            } else {
//                //不存在就直接put
//                objectObjectHashMap.put(applac.getDealername(), objectObjectHashMap1);
//
//            }
        }



//        return list;
//        list.add(objectObjectHashMap);
        System.out.println("生成合同中");
        return  list;
    }

    //确定经销商,确定品牌进行匹配对应合同信息功能
    @Override
    public List<BasicContract> matchTheContractNew(Map<String, Object> resultMap) {
        ArrayList<BasicContract> al = new ArrayList<>();
        String Dealername = (String) resultMap.get("Dealername");
        if(StringUtils.isEmpty(Dealername)){
            throw new BaseException("Dealername不能为空");
        }
        String sector = (String) resultMap.get("sector");
        if(StringUtils.isEmpty(sector)){
            throw new BaseException("sector不能为空");
        }
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        String limitType = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        //根据流程id和经销商和品牌查Approved Limit and Condition的数据
        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        approvedLimitAndCondition.setDealername(Dealername);
        approvedLimitAndCondition.setSector(sector);

        //先判断表Approved Limit and Condition里的limttype为Normal的时候Proposal  limit>0条件成立，走第一个流程

        approvedLimitAndCondition.setLimitType("Normal");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Demo");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsOne = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Temp");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTwo = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Mrg");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsThree = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Cb");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsFour = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        //默认经销商和品牌都确定的情况下limittype不会重复
        ProposalByCommericalAndMarketing alac = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacOne = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacTwo = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacThree = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacFour = new ProposalByCommericalAndMarketing();
        if (StringUtils.isNotEmpty(approvedLimitAndConditions)) {
            alac = approvedLimitAndConditions.get(0);
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsOne)) {
            alacOne = approvedLimitAndConditionsOne.get(0);
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsTwo)) {
            alacTwo = approvedLimitAndConditionsTwo.get(0);
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsThree)) {
            alacThree = approvedLimitAndConditionsThree.get(0);
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsFour)) {
            alacFour = approvedLimitAndConditionsFour.get(0);
        }

        DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
        dealerSectorLimitflag.setDealername(Dealername);
        dealerSectorLimitflag.setSector(sector);
        if(StringUtils.isEmpty(dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag))){
            throw new BaseException("DealerSectorLimitflag表没对应得数据");
        }
        DealerSectorLimitflag dealerSectorLimitflagTwo = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag).get(0);


        if (StringUtils.isNotNull(alac.getProposalLimit()) && alac.getProposalLimit() > 0) {
//            DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
//            dealerSectorLimitflag.setDealerid(dealerId);
//            dealerSectorLimitflag.setSector(sector);
//            DealerSectorLimitflag dealerSectorLimitflagTwo = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag).get(0);
            //判断NormalFlag=true ,就走New application业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getNormalflag().equals("true")) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("4");
                basicContract.setLimittype(alac.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
            } else {
                //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《人民币循环贷款主合同号》
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("人民币循环贷款主合同");//不知道合同号，先用合同名称测试
                if(StringUtils.isEmpty(dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup))){
                    throw new BaseException("DealerSectorContractgroup表没对应得数据");
                }
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);


                if (StringUtils.isEmpty(dealerSectorContractgroups.get(0).getContractnumber())) { //为空就再走New  application业务场景
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(alac.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                } else {
                    if (dealerSectorLimitflagTwo.getThreepartyflag().equals("true")) {
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("6");
                        basicContract.setLimittype(alac.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Three Party Info Change
                    }
                    //此处并行，条件成立可同时出两个业务场景的合同
                        boolean sense = false;
                        //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样就出这个合同Change guarantee conditions
                        GuaranteeInformation guaranteeInformation = new GuaranteeInformation();
                        guaranteeInformation.setInstanceId(instanceId);
                        List<GuaranteeInformation> guaranteeInformations = guaranteeInformationService.selectGuaranteeInformationList(guaranteeInformation);
                        for (GuaranteeInformation gif : guaranteeInformations) {
                            if ((!gif.getCurrentNameCn().equals(gif.getProposalNameCn())) && (!gif.getCurrentNameEn().equals(gif.getProposalNameEn()))) {

                                sense = true;

                            }
                        }
                        if (sense) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("3");
                            basicContract.setLimittype(alac.getLimitType());
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//只要两个值不一样就出这个合同Change guarantee conditions
                        } else {
                            //判断表h_approved_limit_and_condition上的（current里的normallimit+cblimit != proposal里的normallimit+cblimit）或者 （normal上current里的Deposit% ！= proposal里的Deposit%）
                            if ((alac.getApprovedLimit() + alacFour.getApprovedLimit() != alac.getProposalLimit() + alacFour.getProposalLimit()) || (!alac.getApprovedCashDeposit().equals(alac.getProposalCashDeposit()))) {
//                            if((!alac.getCurrentlimit().equals(alac.getAprovedlimit()))&&(!alac.getCurrentsecurityratio().equals(alac.getApprovedsecurityratio()))){
                                BasicContract basicContract = new BasicContract();
                                basicContract.setPriority("2");
                                basicContract.setLimittype(alac.getLimitType());
                                basicContract.setSector(sector);
                                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                            } else {
                                CreditCondition cc = new CreditCondition();
                                cc.setDealername(Dealername);
                                cc.setSector(sector);
                                cc.setLimittype(alac.getLimitType());
                                cc.setInstanceid(instanceId);
                                if(StringUtils.isEmpty(creditConditionService.selectCreditConditionList(cc))){
                                    throw new BaseException("CreditCondition表没对应得数据");
                                }
                                CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                                WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                                wpc.setDealername(Dealername);
                                wpc.setSector(sector);
                                wpc.setCreditType(alac.getLimitType());
                                wpc.setInstanceId(instanceId);
                                if(StringUtils.isEmpty(wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc))){
                                    throw new BaseException("WholesalePerformanceCurrently表没对应得数据");
                                }
                                WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
                                //判断CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就走这个合同
                                if (creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiredDate()) != 0) {
                                    BasicContract basicContract = new BasicContract();
                                    basicContract.setPriority("1");
                                    basicContract.setLimittype(alac.getLimitType());
                                    basicContract.setSector(sector);
                                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Expiry Date extension
                                }
                            }
                        }

                }
            }
        }
        if (StringUtils.isNotNull(alacOne.getProposalLimit()) && alacOne.getProposalLimit() > 0) {  //判断表Approved Limit and Condition里的limttype为demo的时候Proposal  limit>0条件成立，走第二个流程
//            DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
//            dealerSectorLimitflag.setDealerid(dealerId);
//            dealerSectorLimitflag.setSector(sector);
//            DealerSectorLimitflag dealerSectorLimitflagTwo = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag).get(0);
            //判断DemolFlag=true ,就走New application业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getDemolflag().equals("true")) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("4");
                basicContract.setLimittype(alacOne.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
            } else {
                //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《试驾车循环贷款合同号》
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("试驾车循环贷款合同");//不知道合同号，先用合同名称测
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                if (StringUtils.isEmpty(dealerSectorContractgroups.get(0).getContractnumber())) { //为空就再走New  application业务场景
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(alacOne.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                } else {
                    boolean sense = false;
                    //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样就出这个合同Change guarantee conditions
                    GuaranteeInformation guaranteeInformation = new GuaranteeInformation();
                    guaranteeInformation.setInstanceId(instanceId);
                    List<GuaranteeInformation> guaranteeInformations = guaranteeInformationService.selectGuaranteeInformationList(guaranteeInformation);
                    for (GuaranteeInformation gif : guaranteeInformations) {
                        if ((!gif.getCurrentNameCn().equals(gif.getProposalNameCn())) && (!gif.getCurrentNameEn().equals(gif.getProposalNameEn()))) {

                            sense = true;

                        }
                    }
                    if (sense) {
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("3");
                        basicContract.setLimittype(alacOne.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//只要两个值不一样就出这个合同Change guarantee conditions
                    } else {
                        //判断表h_approved_limit_and_condition里的current跟proposal不一致的时候
                        if ((!alacOne.getApprovedLimit().equals(alacOne.getProposalLimit())) || (!alacOne.getApprovedCashDeposit().equals(alacOne.getProposalCashDeposit()))) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("2");
                            basicContract.setLimittype(alacOne.getLimitType());
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                        } else {
                            CreditCondition cc = new CreditCondition();
                            cc.setDealername(Dealername);
                            cc.setSector(sector);
                            cc.setLimittype(alacOne.getLimitType());
                            cc.setInstanceid(instanceId);
                            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                            WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                            wpc.setDealername(Dealername);
                            wpc.setSector(sector);
                            wpc.setCreditType(alacOne.getLimitType());
                            wpc.setInstanceId(instanceId);
                            WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
                            //判断CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就走这个合同
                            if (creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiredDate()) != 0) {
                                BasicContract basicContract = new BasicContract();
                                basicContract.setPriority("1");
                                basicContract.setLimittype(alacOne.getLimitType());
                                basicContract.setSector(sector);
                                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Expiry Date extension
                            }
                        }
                    }

                }
            }

        }
        if (StringUtils.isNotNull(alacTwo.getProposalLimit()) && alacTwo.getProposalLimit() > 0) {  //判断表Approved Limit and Condition里的limttype为temp的时候Proposal  limit>0条件成立，走第三个流程
            //判断TempFlag=true ,就走Temp Limit业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getTempflag().equals("true")) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("7");
                basicContract.setLimittype(alacTwo.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Temp Limit
            } else {
                boolean sense = false;
                //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样或者--->
                GuaranteeInformation guaranteeInformation = new GuaranteeInformation();
                guaranteeInformation.setInstanceId(instanceId);
                List<GuaranteeInformation> guaranteeInformations = guaranteeInformationService.selectGuaranteeInformationList(guaranteeInformation);
                for (GuaranteeInformation gif : guaranteeInformations) {
                    if ((!gif.getCurrentNameCn().equals(gif.getProposalNameCn())) && (!gif.getCurrentNameEn().equals(gif.getProposalNameEn()))) {
                        sense = true;
                    }
                }
                //表h_approved_limit_and_condition里的current跟proposal不一致的时候或者--->
                if ((!alacTwo.getApprovedLimit().equals(alacTwo.getProposalLimit()))) {
                }
                CreditCondition cc = new CreditCondition();
                cc.setDealername(Dealername);
                cc.setSector(sector);
                cc.setLimittype(alacTwo.getLimitType());
                cc.setInstanceid(instanceId);
                CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                wpc.setDealername(Dealername);
                wpc.setSector(sector);
                wpc.setCreditType(alacTwo.getLimitType());
                wpc.setInstanceId(instanceId);
                WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
                //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出Temp Limit这个合同
                if (sense || (!alacTwo.getApprovedLimit().equals(alacTwo.getProposalLimit())) || creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiredDate()) != 0) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("7");
                    basicContract.setLimittype(alacTwo.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Temp Limit
                }
            }
        }
        if (StringUtils.isNotNull(alacThree.getProposalLimit()) && alacThree.getProposalLimit() > 0) {  //判断表Approved Limit and Condition里的limttype为mrg的时候Proposal  limit>0条件成立，走第四个流程
            //判断MRGFlag=true ,就走MRG limit业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getMrgflag().equals("true")) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("8");
                basicContract.setLimittype(alacThree.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同MRG limit
            } else {
                //表h_approved_limit_and_condition里的current跟proposal不一致的时候或者--->
//                if ((!alacThree.getCurrentlimit().equals(alacThree.getAprovedlimit()))) {}
                CreditCondition cc = new CreditCondition();
                cc.setDealername(Dealername);
                cc.setSector(sector);
                cc.setLimittype(alacThree.getLimitType());
                cc.setInstanceid(instanceId);
                CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                wpc.setDealername(Dealername);
                wpc.setSector(sector);
                wpc.setCreditType(alacThree.getLimitType());
                wpc.setInstanceId(instanceId);
                WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
                //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出MRG limit这个合同
                if ((!alacThree.getApprovedLimit().equals(alacThree.getProposalLimit())) || creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiredDate()) != 0) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("8");
                    basicContract.setLimittype(alacThree.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同MRG limit
                }
            }
        }
        if (StringUtils.isNotNull(alacFour.getProposalLimit()) && alacFour.getProposalLimit() > 0) {  //判断表Approved Limit and Condition里的limttype为cb的时候Proposal  limit>0条件成立，走第五个个流程
            //判断CBFlag=true ,就走New application业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getCbflag().equals("true")) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("4");
                basicContract.setLimittype(alacFour.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
            } else {
                //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《CB改装车协议(循环)》或者--->
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("CB改装车协议(循环)");//不知道合同号，先用合同名称测
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
//                if (StringUtils.isEmpty(dealerSectorContractgroups)) {
                boolean sense = false;
                //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样
                GuaranteeInformation guaranteeInformation = new GuaranteeInformation();
                guaranteeInformation.setInstanceId(instanceId);
                List<GuaranteeInformation> guaranteeInformations = guaranteeInformationService.selectGuaranteeInformationList(guaranteeInformation);
                for (GuaranteeInformation gif : guaranteeInformations) {
                    if ((!gif.getCurrentNameCn().equals(gif.getProposalNameCn())) && (!gif.getCurrentNameEn().equals(gif.getProposalNameEn()))) {
                        sense = true;
                    }
                }
                if (sense || StringUtils.isEmpty(dealerSectorContractgroups.get(0).getContractnumber())) { //合同号为空或者currentname跟proposalname两个值不一样就再走New  application业务场景
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(alacFour.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                } else {
                    CreditCondition cc = new CreditCondition();
                    cc.setDealername(Dealername);
                    cc.setSector(sector);
                    cc.setLimittype(alacFour.getLimitType());
                    cc.setInstanceid(instanceId);
                    CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                    WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                    wpc.setDealername(Dealername);
                    wpc.setSector(sector);
                    wpc.setCreditType(alacFour.getLimitType());
                    wpc.setInstanceId(instanceId);
                    WholesalePerformanceCurrently wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc).get(0);
                    //判断表h_approved_limit_and_condition里的current跟proposal不一致的时候或者CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期
                    if ((!alacFour.getApprovedLimit().equals(alacFour.getProposalLimit())) || (!alacFour.getApprovedCashDeposit().equals(alacFour.getProposalCashDeposit())) || creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiredDate()) != 0) {
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("2");
                        basicContract.setLimittype(alacFour.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                    }
                }
            }

        }
        if(StringUtils.isEmpty(al)){
            throw new BaseException("没有对应条件的数据！");
        }
    return al;
    }

    @Override
    public int contractnew(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }

        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupby(approvedLimitAndCondition);
        for(ProposalByCommericalAndMarketing applac : approvedLimitAndConditions) {
            Map<String, Object> map = new HashMap<>();
            map.put("Dealername", applac.getDealername());
            map.put("sector", applac.getSector());
            map.put("instanceId", instanceId);
            List<BasicContract> basicContracts = this.matchTheContractNew(map);
            //把生成的合同数据全部存入dealercode_contract表中，以便后续回看历史记录
            DealercodeContract dealercodeContract = new DealercodeContract();
            dealercodeContract.setDealerNameCN(applac.getDealername());
            dealercodeContract.setSector(applac.getSector());
            dealercodeContract.setInstanceId(instanceId);
            for (BasicContract bc : basicContracts){
                dealercodeContract.setContractName(bc.getContractname());
                dealercodeContract.setContractLocation(bc.getContractlocation());
                dealercodeContract.setLimitType(bc.getLimittype());
                dealercodeContract.setPriority(bc.getPriority());
                //其中个别合同需要生成合同号
                //调用方法获取dealercode
                String dealercodelist = dealercodelist(instanceId, applac.getDealername(), applac.getSector());
                if(bc.getContractname().equals("人民币循环贷款合同")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "F");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("浮动抵押")){
                    String f = maincontractno(dealercodelist, "M");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("三方")||bc.getContractname().equals("三方-C")||bc.getContractname().equals("三方-E")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "W");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("主信托")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "T");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("个人保函")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "G");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("企业保函")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "C");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("试乘试驾车贷款合同")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "DEMO");
                    dealercodeContract.setContract(f);
                }
                if(bc.getContractname().equals("试驾车个人保函")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "DEMO");
                    dealercodeContract.setContract(f+"-G");
                }
                if(bc.getContractname().equals("试驾车企业保函")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "DEMO");
                    dealercodeContract.setContract(f+"-C");
                }
                if(bc.getContractname().equals("DEMO抵押合同")){
                    //调用方法拼出主合同号
                    String f = maincontractno(dealercodelist, "DEMO");
                    dealercodeContract.setContract(f+"-M");
                }
                dealercodeContractService.insertDealercodeContract(dealercodeContract);
            }


        }
//        return list;
//        list.add(objectObjectHashMap);
        System.out.println("生成合同中");
        return  1;
    }

    /**
     * 生成001的编号
     *
     * @param maxNum 最大数
     * @param count  累计的
     * @return
     */
    public static String sequenceCode(Long maxNum, Long count) {
        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 >= strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    }

    /**
     * 获取流程下对应得dealercode
     */
    public String dealercodelist(String instanceId,String dealerNameCN,String sector) {
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setInstanceId(instanceId);
        basicInformation.setDealerNameCN(dealerNameCN);
        List<BasicInformation> basicInformations = basicInformationService.selectBasicInformationList(basicInformation);
        if(StringUtils.isEmpty(basicInformations)){
            throw new BaseException("BasicInformation没对应得数据");
        }
        BasicInformation basicInformation1 = basicInformations.get(0);
        String sector1 = basicInformation1.getSector();
        String dealerCodeFromWFS = basicInformation1.getDealerCodeFromWFS();
        String[] split = sector1.split(",");
        String[] splits = dealerCodeFromWFS.split(",");
        String dealercode = "";
        for (int i = 0; i <split.length ; i++) {
            if(split[i].equals(sector)){
                for (int j = 0; j <splits.length ; j++) {
                    dealercode = splits[i];
                }
            }
        }
        return dealercode;
    }

    /**
     * 拼主合同号
     */
    public String maincontractno (String dealercode,String letter) {
        DealercodeCount dealercodeCount = new DealercodeCount();
        dealercodeCount.setDealercode(dealercode);
        dealercodeCount.setTemp(letter);
        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
        if(StringUtils.isEmpty(dealercodeCounts)){
            dealercodeCount.setTemp(letter);
            dealercodeCount.setCount((long) 1);
            dealercodeCountService.insertDealercodeCount(dealercodeCount);
        }

        //拼人民币循环贷款主合同号
        String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        String month = new SimpleDateFormat("M", Locale.CHINESE).format(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        try {
            month = new SimpleDateFormat("MMMMM", Locale.US).format((new SimpleDateFormat("MM")).parse(month));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DealercodeCount dealercodeCount1 = dealercodeCountService.selectDealercodeCountList(dealercodeCount).get(0);
        Long count = dealercodeCount1.getCount();
        String code = sequenceCode((long) 1000, count);
        //用完这个字段开始自增，并且自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
//        BeanUtil.copyProperties(dealercodeCount1,dealercodeCount);
//        if(count+1>999 || dateNowStr.equals("01-01")){
//            dealercodeCount.setCount((long)1);
//        }else {
//
//            dealercodeCount.setCount(count+1);
//        }
//        dealercodeCountService.updateDealercodeCount(dealercodeCount);
        //TODO 用变量
        String contrctcode = dealercode+letter+year+month+code;
        return contrctcode;
    }

}
